#include "SeqList.h"


void SeqListInit(SeqList* psl)
{
	assert(psl != NULL);

	psl->a = NULL;
	psl->capacity = 0;
	psl->size = 0;
}

void SeqListDestroy(SeqList* psl)
{
	assert(psl != NULL);

	free(psl->a);
	psl->a = NULL;
	psl->capacity = 0;
	psl->size = 0;
}

void SeqListPrint(SeqList* psl)
{
	assert(psl != NULL);

	for (int i = 0; i < psl->size; i++)
	{
		printf("%d ", psl->a[i]);
	}
	printf("\n");
}

void CheckCapacity(SeqList* psl)
{
	assert(psl != NULL);

	if (psl->capacity == psl->size)
	{
		int newcapacity = psl->capacity == 0 ? 4 : psl->capacity * 2;
		psl->capacity = newcapacity;
		SeqListDataType* tmp = realloc(psl->a, sizeof(SeqListDataType) * psl->capacity);
		if (tmp == NULL)
		{
			perror("SeqListPushBack");
			return;
		}
		psl->a = tmp;
	}
}

void SeqListPushBack(SeqList* psl, SeqListDataType x)
{
	assert(psl != NULL);

	CheckCapacity(psl);

	psl->a[psl->size] = x;
	psl->size++;
}

void SeqListPopBack(SeqList* psl)
{
	assert(psl != NULL);
	assert(psl->size > 0);

	psl->size--;
}

void SeqListPushFront(SeqList* psl, SeqListDataType x)
{
	assert(psl != NULL);

	CheckCapacity(psl);

	for (int i = psl->size - 1; i >= 0; i--)
	{
		psl->a[i + 1] = psl->a[i];
	}

	psl->a[0] = x;
	psl->size++;
}

void SeqListPopFront(SeqList* psl)
{
	assert(psl != NULL);
	assert(psl->size > 0);

	for (int i = 0; i < psl->size - 1; i++)
	{
		psl->a[i] = psl->a[i + 1];
	}

	psl->size--;
}

void SeqListInsert(SeqList* psl, int pos, SeqListDataType x)
{
	assert(psl != NULL);
	assert(pos >= 0 && pos <= psl->size);

	for (int i = psl->size - 1; i >= pos; i--)
	{
		psl->a[i + 1] = psl->a[i];
	}

	psl->a[pos] = x;
	psl->size++;
}

void SeqListErase(SeqList* psl, int pos)
{
	assert(psl != NULL);
	assert(pos >= 0 && pos < psl->size);

	for (int i = pos; i < psl->size - 1; i++)
	{
		psl->a[i] = psl->a[i + 1];
	}

	psl->size--;
}

int SeqListFind(SeqList* psl, SeqListDataType x)
{
	assert(psl != NULL);

	for (int i = 0; i < psl->size; i++)
	{
		if (psl->a[i] == x)
			return 1;
	}

	return 0;
}


